#pragma once
#include <iostream>
using namespace std;
#include <pthread.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <cstring>
#include <string.h>
#include <netinet/in.h>
#include <string>
#include <arpa/inet.h>

namespace Client
{
    class tcpClient
    {
    public:
        tcpClient(const string &ip, const uint16_t &port) :  _server_ip(ip), _server_port(port),_sockfd(-1)
        {
        }
        void initClient()
        {
            // 1:打开套接字
            _sockfd = socket(AF_INET, SOCK_STREAM, 0);
            if (_sockfd < 0)
            {
                perror("socket errno\n");
                exit(1);
            }
            printf("socket success\n");
        }
        void start()
        {
            // 建立连接
            sockaddr_in server;
           //bzero(&server, sizeof(server));
           memset(&server,0,sizeof(server));
            //socklen_t len = sizeof(server);
            server.sin_family = AF_INET;
            server.sin_port = htons(_server_port);
            server.sin_addr.s_addr = inet_addr(_server_ip.c_str());
            int n = connect(_sockfd, (sockaddr *)&server,sizeof(server));
            
            if(n < 0){
                perror("connect errno\n");
                
            }
            else
            {
                printf("connect success\n");
                string line;
                while (1)
                {
                    cout << "请输入#";
                    getline(cin, line);
                    write(_sockfd, line.c_str(), sizeof(line)); // 向服务器发送数据

                    char inbuffer[128];
                    int ret = read(_sockfd, inbuffer, sizeof(inbuffer) - 1);
                    if (ret > 0)
                    {
                        inbuffer[ret] = 0;
                        cout << "Server回显：" << inbuffer << endl;
                    }
                    else
                    {
                        break;
                    }
               
                }
            }
        }

        ~tcpClient()
        {
            if (_sockfd >= 0)
                close(_sockfd);
        }

    private:
        int _sockfd;
        string _server_ip;
        uint16_t _server_port;
    };
}